<?php

namespace app\info\controller;

use app\info\model\QuestionModel;
use app\info\model\QuestionnaireItemModel;
use app\info\model\QuestionnaireModel;
use Exception;
use think\admin\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class QuestionStatic extends Controller
{
    /**
     * 当前操作数据库
     * @var string
     */
    private string $table = 'Question';

    /**
     * 调查问卷数据管理
     * @auth true
     * @menu true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        $this->title = '调查问卷数据管理';
        $query = $this->_query(QuestionnaireModel::class);
        // 加载对应数据
        $this->typeOf = $this->request->get('typeOf', 'index');
        if ($this->typeOf == 'index') $query->where(['is_deleted' => 0]);
        elseif ($this->typeOf == 'is_deleted') $query->where(['is_deleted' => 1]);
        $query->like('name,span')->order('id desc')->page(true, true);
    }

    /**
     * 查看详情
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function detail()
    {
        $this->title = '问卷调查数据统计';
        $id = $this->request->get('id');
        $model = new QuestionModel();
        $list = $model->where(['qid' => $id])->select();
        $list = $list->toArray();

        $data = [];
        $m1 = new QuestionnaireItemModel();

        $ns = $m1->where(['qid' => $id])->select();


        foreach ($list as $value) {
            $item = json_decode($value['content'], true);
            $nn = [];
            foreach ($ns as $n) {
                foreach ($item as $i) {
                    if ($n['id'] == $i['id']) {
                        $nn[$n['name']] = $i['select'];
                    }
                }
            }
            $a = [
                '姓名' => $value['name'],
                '手机号' => $value['tel'],
                '房屋号' => $value['house']
            ];

            $data[] = array_merge($a, $nn);
        }
        $keys = [
            '姓名','手机号','房屋号'
        ];

        $k1 = array_column($ns->toArray(),'name');
        $keys = array_merge($keys, $k1);

        $this->fetch('item', ['list' => $data, 'qid' => $id, 'keys' => $keys]);
    }

    /**
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function export(){
        $id = $this->request->get('id');
        //获取数据
        $model = new QuestionModel();
        $list = $model->where(['qid' => $id])->select();
        $list = $list->toArray();

        $data = [];
        $m1 = new QuestionnaireItemModel();

        $ns = $m1->where(['qid' => $id])->select();


        foreach ($list as $value) {
            $item = json_decode($value['content'], true);
            $nn = [];
            foreach ($ns as $n) {
                foreach ($item as $i) {
                    if ($n['id'] == $i['id']) {
                        $nn[$n['name']] = $i['select'];
                    }
                }
            }
            $a = [
                '姓名' => $value['name'],
                '手机号' => $value['tel'],
                '房屋号' => $value['house']
            ];

            $data[] = array_merge($a, $nn);
        }
        $keys = [
            '姓名','手机号','房屋号'
        ];

        $k1 = array_column($ns->toArray(),'name');
        $keys = array_merge($keys, $k1);

        //文件定义
        $date = date("Y_m_d", time());
        $fileName = '调查问卷数据';
        $fileName .= "_{$date}.xls";

        $header = $keys;
        $listVal = [];
        foreach ($data as $kk => $datum){
            $i = [];
            foreach ($header as $value){
                $i[] = $datum[$value];
            }
            $listVal[] = $i;
        }

        $re = $this->downloadXLSX($fileName, $header, $listVal);

        if($re){
            $this->success('数据导出成功');
        }else{
            $this->error('数据为空');
        }

    }


    function getTmpDir(): string
    {
        $tmp = ini_get('upload_tmp_dir');

        if ($tmp !== False && file_exists($tmp)) {
            return realpath($tmp);
        }

        return realpath(sys_get_temp_dir());
    }

    /**
     * download xlsx file
     *
     * @param string $filename
     * @param array $header
     * @param array $list
     * @return string err msg
     * @throws Exception
     */
    function downloadXLSX(string $filename, array $header, array $list): string
    {
        try {
            $config = ['path' => $this->getTmpDir() . '/'];
            $excel  = (new \Vtiful\Kernel\Excel($config))->fileName($filename.'.xlsx', 'Sheet1');
            $fileHandle = $excel->getHandle();
            $format1    = new \Vtiful\Kernel\Format($fileHandle);
            $format2    = new \Vtiful\Kernel\Format($fileHandle);

            // title style
            $titleStyle = $format1->fontSize(16)
                ->bold()
                ->font("Calibri")
                ->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)
                ->toResource();

            // global style
            $globalStyle = $format2->fontSize(10)
                ->font("Calibri")
                ->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)
                ->border(\Vtiful\Kernel\Format::BORDER_THIN)
                ->toResource();

            $headerLen = count($header);

            // header
            array_unshift($list, $header);

            // title
            $title = array_fill(1, $headerLen - 1, '');
            $title[0] = $filename;
            array_unshift($list, $title);

            $end = strtoupper(chr(65 + $headerLen - 1));
            // column style
            $excel->setColumn("A:{$end}", 15, $globalStyle);
            // title
            $excel->MergeCells("A1:{$end}1", $filename)->setRow("A1", 25, $titleStyle);
            // 冻结前两行，列不冻结
            $excel->freezePanes(2, 0);
            // 数据
            $filePath = $excel->data($list)->output();

            header("Content-Disposition:attachment;filename={$filename}.xlsx");

            $re = copy($filePath, 'php://output');
            if ($re === false) {
                $err = 'failed to write output';
            } else {
                $err = '';
            }
            @unlink($filePath);

            return $err;
        } catch (\Vtiful\Kernel\Exception $e) {
            return $e->getMessage();
        }
    }
}